//
//  HNAssignmentVC.m
//  优学荟管理系统
//
//  Created by edz on 2017/12/25.
//  Copyright © 2017年 星道三好. All rights reserved.
//
#import "SAWAlertView.h"
#import "SAWHomeworkModel.h"
#import "HNAssignmentVC.h"
#import "CourseEvaluateAudioView.h"
#import "EMCDDeviceManager.h"
#import "MBSmartVideoView.h"
#import "MyHappyTimeVC.h"
#import "XZNotificationModel.h"
#import <SDWebImage/UIButton+WebCache.h>
#import "ImgZoom.h"
#import "EMCDDeviceManager.h"

/** 图片总量 */
static NSInteger const ImgCount = 3;

@interface HNAssignmentVC ()<UITextFieldDelegate, UITextViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIWebViewDelegate>
{
    // 上传按钮
    __weak IBOutlet UIButton *_UploadFileBtn;
    // 上传按钮的父视图
    __weak IBOutlet UIView *_UploadFileView;
    // 上传按钮的信息View
    __weak IBOutlet UIView *_UploadFileInfoView;
    // 上传按钮的左间距
    __weak IBOutlet NSLayoutConstraint *_UploadFileBtnLeft;
}
@property (weak, nonatomic) IBOutlet UIButton *moreKnowlageBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *_ContentViewHeight;
@property (weak, nonatomic) IBOutlet UITextField *_Title;
@property (weak, nonatomic) IBOutlet UITextView *_Content;
@property (weak, nonatomic) IBOutlet UILabel *_ContentPlaceHolder;
@property (weak, nonatomic) IBOutlet UIButton *_Sure;
@property (nonatomic, assign) BOOL SaveVideo;
@property (nonatomic, strong)SAWHomeworkModel *homeworkModel;
@property (weak, nonatomic) IBOutlet UILabel *remind;

// 相册摄像机
@property (nonatomic, strong) UIImagePickerController *ImagePicker;
// 图片按钮
@property (nonatomic, strong)  NSMutableArray <UIButton *>*ImgBtns;
// 图片存储地直,@[@{key:Button}]
@property (nonatomic, strong) NSMutableArray *ImgArr;
// 那个图片的按钮
@property (nonatomic, strong) UIButton *TempButton;
// 视频的存储，@[@{Button.tag:@{@"url":url,@"img":img}}]
@property (nonatomic, strong) NSMutableArray *VideoDict;
@property (nonatomic, assign) NSInteger Tag;

@property (weak, nonatomic) IBOutlet UITextField *knowlageFile;


@property (nonatomic, strong) XZNotificationModel *model;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) NSString *mp3URL;

@property(nonatomic,copy)NSString *knowledName;
@property(nonatomic,copy)NSString *knowledID;
@end

@implementation HNAssignmentVC {
    BOOL _isOpen;
}
- (IBAction)moreKnowlageBtn:(UIButton *)sender {
    
    [self.homeworkModel getKnowLage:self.LessonId succed:^(NSArray *dataArr) {
        if (dataArr.count>0) {
         
            SAWAlertView *alert = [[SAWAlertView alloc]initWithdataArr:dataArr withType:8];
            alert.selecItem = ^(NSString *item,NSString *type) {
                _knowlageFile.text = item;
                _knowledName = item;
                _knowledID = type;
            };
            [alert show];
        }
        
    }];
    
}
-(SAWHomeworkModel *)homeworkModel
{
    if (!_homeworkModel) {
        _homeworkModel = [[SAWHomeworkModel alloc]init];
    }
    return _homeworkModel;
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(255, 255, 255)] forBarMetrics:(UIBarMetricsDefault)];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(51,51,51)}];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(255,255,255)}];
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(47, 204, 138)] forBarMetrics:(UIBarMetricsDefault)];
    
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    if (self.type == HNAssignmentTypeOperation) {
        self.title = @"布置作业";
        self._Title.placeholder = @"请输入作业标题";
        self._ContentPlaceHolder.text = @"请输入作业内容";
        self.remind.text = @"添加图片作业说明";
    } else if (self.type == HNAssignmentTypeNotice) {
        self.title = @"发布通告" ;
        self._Title.placeholder = @"请输入通告标题";
        self._ContentPlaceHolder.text = @"请输入通告内容";
        self.remind.text = @"添加通告说明";
    } else {
        self.title = @"编辑作业";
        [self getTask];
    }
    
    self._ContentViewHeight.constant *= KScale;
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTargat:self action:@selector(Pop) image:@"icon_back_student_sign" highImage:@"icon_back_student_sign"];
    [self TextFieldDidChange:self._Title];
}

- (void)getTask {
    //http://192.168.0.223:8080/StarShine/ys/assignHomework.do?action=getHomeWorkById&id=99
    
    NSString *url = [NSString stringWithFormat:@"assignHomework.do?action=getHomeWorkById2&id=%@",self.ID];
    NSLog(@"%@ - %@",LLBaseURL(url), [AccountTool shareAccountTool].currentAccount.authCode);
    [MBProgressHUD showHUD];
    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        if ([Obj[@"code"] integerValue] == 1000) {
            NSDictionary *dict = Obj[@"t"];
            
            self.model = [[XZNotificationModel alloc] init_ValuForKeyWithDict:dict];
            
            self._Title.text = _model.title;
            self._Content.text = _model.content;
            self._ContentPlaceHolder.hidden = self._Content.text.length != 0 ? YES : NO;
            [self._Sure setEnabled:YES];
            
            /// 判断是否有视频url
            if (self.model.video != nil && ![self.model.video isKindOfClass:[NSNull class]] && self.model.video.length > 0) {
                UIButton *Button = [self CreatImgBtn:nil];
                [Button sd_setBackgroundImageWithURL:[NSURL URLWithString:self.model.videoImg] forState:(UIControlStateNormal) placeholderImage:[UIImage imageNamed:@"bg_img_homework_picture_default"]];
                [self.VideoDict addObject:@{@(Button.tag):@{@"url":self.model.video,@"img":self.model.videoImg}}];
                self.SaveVideo = YES;
            }
            ///不等于数组直接return
            if (![self.model.paths isKindOfClass:[NSArray class]]) return;
            
            /// 循环判断 音频 和 照片
            [self.model.paths enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString *Str = [obj pathExtension];
                NSArray *image = [obj componentsSeparatedByString:@"/"];
                NSString *imageName = [image.lastObject componentsSeparatedByString:@"."].firstObject;
                if ([Str isEqualToString:@"png"] || [Str isEqualToString:@"jpg"]) {
                    // 新建按钮的
                    UIButton *Button = [self CreatImgBtn:nil];
                    [Button sd_setBackgroundImageWithURL:[NSURL URLWithString:obj] forState:(UIControlStateNormal) placeholderImage:[UIImage imageNamed:@"bg_img_homework_picture_default"]];
                    Button.tag = 1001;
                    // 加入数组
                    [self.ImgArr addObject:@{imageName:Button}];
                    
                } else if ([Str isEqualToString:@"amr"] || [Str isEqualToString:@"mp3"]) {
                    // 新建按钮的
                    UIButton *Button = [self CreatImgBtn:[UIImage imageNamed:@"btn_mp3"]];
                    Button.tag = 1002;
                    self.mp3URL = obj;
                    // 加入数组
                    [self.ImgArr addObject:@{imageName:Button}];
                }
            }];
            
            
        }else {
            [MBProgressHUD showError:Obj[@"msg"]];
        }
        [MBProgressHUD hideHUD];
    } Fail:^(NSError *Error) {
        [MBProgressHUD hideHUD];
    }];
}

#pragma mark - 网络
// 上传图片
- (void)UploadImg:(UIImage *)Img Complete:(void(^)(NSString *ImgName))Complete
{
    [MBProgressHUD showHUD];
    [NetManager UpdataImgWithURL:LLBaseURLTeacher(@"upload.do") Img:Img parameter:@{@"action":@"uploadimage"} success:^(id obj) {
        
        __block NSString *Str = [[NSString alloc] initWithData:obj encoding:NSUTF8StringEncoding];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            Str = [Str stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
            Str = [Str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            // 上传成功，设置图片
            Complete (Str);
        });
        
    } fail:^(NSError *error) {
        [MBProgressHUD showError:@"图片上传失败"];
    }];
}


#pragma mark - 事件
- (void)Pop {
    
    [self.navigationController popViewControllerAnimated:YES];
}

/** 点击了图片事件 */
- (IBAction)ClickImageAction:(UIButton *)sender {
    
    self.TempButton = sender;
    NSArray *Arr = nil;
    if (self.SaveVideo) {
        
        Arr = @[@"图片上传",@"音频上传"];
    } else {
        
        Arr = @[@"图片上传",@"音频上传",@"视频上传"];
    }
    [self AlertControllerOfTitle:@"请选择操作项" StringArr:Arr CallBack:^(NSInteger Index, NSString *Str) {
        
        // 图片
        if ([Str isEqualToString:@"图片上传"] && Index == 0) {
            
            [self ClickImage:sender];
        }
        
        // 音频
        if ([Str isEqualToString:@"音频上传"] && Index == 1) {
            
            [self ClickAudio:sender];
        }
        
        // 视频
        if ([Str isEqualToString:@"视频上传"] && Index == 2) {
            
            [self ClickVideo:sender];
        }
    }];
}

#pragma mark - TextField代理 TextView代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    return YES;
}

- (void)TextFieldDidChange:(UITextField *)TextField {
    
    [self._Sure setEnabled:self._Content.text.length > 0 && self._Title.text.length > 0 ? YES:NO];
}

- (void)textViewDidChange:(UITextView *)textView {
    
    [self._Sure setEnabled:self._Content.text.length > 0 && self._Title.text.length > 0 ? YES:NO];
    self._ContentPlaceHolder.hidden = textView.text.length > 0 ? YES:NO;
}


#pragma mark - Func
/** 将需要展示的内容放进数组里，回调事件的顺序Index及相对应的Str */
- (void)AlertControllerOfTitle:(NSString *)Title StringArr:(NSArray <NSString *>*)StringArr CallBack:(void (^)(NSInteger Index, NSString *Str))CallBack {
    
    UIAlertController *Alert = [UIAlertController alertControllerWithTitle:Title message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    [StringArr enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [Alert addAction:[UIAlertAction actionWithTitle:obj style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            CallBack ? CallBack(idx, obj) : nil;
        }]];
    }];
    [Alert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    [self presentViewController:Alert animated:YES completion:nil];
}



/** 移动上传按钮的左间距，YES增加 NO减 */
- (void)MoveUploadFileBtnLeftOfAdd:(BOOL)Add Button:(UIButton *)Button {
    
    
    // 移动固定的那个窗口
    [UIView animateWithDuration:0.3 animations:^{
        
        _UploadFileBtnLeft.constant = Add ? (_UploadFileBtnLeft.constant + _UploadFileBtn.frame.size.width + 15):(_UploadFileBtnLeft.constant - _UploadFileBtn.frame.size.width - 15);
        [_UploadFileBtn layoutIfNeeded];
        _UploadFileBtn.alpha = self.ImgBtns.count >= ImgCount && Add == YES ? 0:1;
        _UploadFileInfoView.alpha = self.ImgBtns.count >= 1 && Add == YES ? 0:1;
    }];
    
    
    // 位置变动
    if (Add == NO) {
        // 如果这个按钮在数组里存在就开始执行删除操作
        [self.ImgBtns containsObject:Button] ? [self.ImgBtns removeObject:Button]:nil;
        [Button removeFromSuperview];
        // 数组某个对象移除成功后重新将所有元素排版
        [self.ImgBtns enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj mas_updateConstraints:^(MASConstraintMaker *make) {
                
                make.left.equalTo(_UploadFileView).offset(15 * (idx + 1) + (idx *_UploadFileBtn.frame.size.width));
            }];
        }];
        [UIView animateWithDuration:0.3 animations:^{
            [_UploadFileView layoutIfNeeded];
        }];
    }
    
    
    
    
}

/** 新建按钮的 */
- (UIButton *)CreatImgBtn:(UIImage *)Image {
    
    UIButton *Button = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [Button setBackgroundImage:Image forState:(UIControlStateNormal)];
    Button.tag = self.Tag;
    self.Tag ++;
    [Button addTarget:self action:@selector(DeleteImgBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    [_UploadFileView addSubview:Button];
    [Button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.width.equalTo(_UploadFileBtn);
        make.left.equalTo(_UploadFileView.mas_left).offset(_UploadFileBtnLeft.constant);
    }];
    [self.ImgBtns addObject:Button];
    
    if (self.type == HNAssignmentTypeModifying) {
        UIButton *deletButton = [[UIButton alloc] init];
        [deletButton setBackgroundImage:[UIImage imageNamed:@"pop_deleted_default"] forState:(UIControlStateNormal)];
        [deletButton addTarget:self action:@selector(delegateImage:) forControlEvents:(UIControlEventTouchUpInside)];
        [Button addSubview:deletButton];
        
        [deletButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.top.equalTo(Button);
            make.size.mas_equalTo(CGSizeMake(15, 15));
        }];
    }
    
    [self MoveUploadFileBtnLeftOfAdd:YES Button:nil];
    return Button;
}

- (void)delegateImage:(UIButton *)sender {
    _isOpen = YES;
    
    UIButton *button = (UIButton *)sender.superview;
    [self DeleteImgBtn:button];
}

/** 删除按钮 */
- (void)DeleteImgBtn:(UIButton *)Button {
    
    if (_isOpen == YES) {
        [self deleteButton:Button];
        _isOpen = NO;
    } else if (self.type == HNAssignmentTypeModifying) {
        [self play:Button];
    } else {
        [self deleteButton:Button];
    }
    
}

/** YES:url NO:img */
- (NSString *)GetVideoStr:(BOOL)IsUrl {
    
    NSMutableArray *Arr = [NSMutableArray array];
    [self.VideoDict enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSDictionary *Dict = [[obj allValues] firstObject];
        NSArray *arr =[Dict allValues];
        [Arr addObject: IsUrl ? [arr firstObject]:[arr lastObject]];
    }];
    return [Arr componentsJoinedByString:@","];
}

#pragma mark - 点击了图片上传
- (void)ClickImage:(UIButton *)Button {
    
    [self AlertControllerOfTitle:@"请选择图片选择方式" StringArr:@[@"拍摄", @"从相册中选择"] CallBack:^(NSInteger Index, NSString *Str) {
        if (Index == 0) {
            
            self.ImagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:self.ImagePicker animated:YES completion:nil];
        }
        
        if (Index == 1) {
            
            self.ImagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            [self presentViewController:self.ImagePicker animated:YES completion:nil];
        }
    }];
}

/** 确定 */
- (IBAction)Sure:(id)sender {
    
    [MBProgressHUD showHUD];
    
    // 图片地址
    NSMutableArray *ImgUrlArr = [NSMutableArray array];
    [self.ImgArr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [ImgUrlArr addObject:obj.allKeys[0]];
    }];
    
    NSString *action = @"";
    NSString *msg = @"";
    switch (self.type) {
        case HNAssignmentTypeModifying:
            action = @"updateHomeWork";
            msg = @"修改作业成功";
            break;
        case HNAssignmentTypeOperation:
            action = @"saveHomeWork";
            msg = @"布置作业成功";
            break;
        case HNAssignmentTypeNotice:
            action = @"saveOrganizationAnnunciate";
            msg = @"发布通告成功";
            break;
        default:
            break;
    }
     NSDictionary *Params;
    if (_knowledName.length>0) {
        Params = @{
                   @"knowledgeId" :[_knowledName isEqualToString:_knowlageFile.text] ? _knowledID : @"0",
                   @"knowledgeName" : [_knowledName isEqualToString:_knowlageFile.text] ? @"" : _knowlageFile.text,
                   @"action"  :action,
                   @"title"   :self._Title.text,
                   @"content" :self._Content.text,
                   @"files"   :[ImgUrlArr componentsJoinedByString:@","],
                   @"video"   :[self GetVideoStr:YES],
                   @"videoImg":[self GetVideoStr:NO],
                   @"uids"    :self.type == HNAssignmentTypeModifying ? @"0" : self.Uids,
                   @"lessonId": self.type == HNAssignmentTypeOperation ? self.LessonId : @"0",
                   @"id":self.type == HNAssignmentTypeModifying ? self.ID : @"0"
                   };
    }
    if (_knowledName.length==0) {
        Params = @{
                   @"knowledgeId" :@"0",
                   @"knowledgeName" : _knowlageFile.text,
                   @"action"  :action,
                   @"title"   :self._Title.text,
                   @"content" :self._Content.text,
                   @"files"   :[ImgUrlArr componentsJoinedByString:@","],
                   @"video"   :[self GetVideoStr:YES],
                   @"videoImg":[self GetVideoStr:NO],
                   @"uids"    :self.type == HNAssignmentTypeModifying ? @"0" : self.Uids,
                   @"lessonId": self.type == HNAssignmentTypeOperation ? self.LessonId : @"0",
                   @"id":self.type == HNAssignmentTypeModifying ? self.ID : @"0"
                   };
    }
   
    [NetManager Post:LLBaseURL(@"assignHomework.do") Auth:YES Params:Params Success:^(id Obj) {
        
        if ([Obj[@"code"] integerValue] == 1000) {
            [MBProgressHUD showSuccess:msg];
            
            /// 修改作业回去的回调
            if (_ReloadBack) {
                _ReloadBack(self.index);
            }
            
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            [MBProgressHUD showError:Obj[@"msg"]];
        }
        
    
        
    } Fail:^(NSError *Error) {
        [MBProgressHUD showError:NetErr];
    }];
}
#pragma mark - 点击了音频上传
- (void)ClickAudio:(UIButton *)Button {
    
    // 得到音频的数据了
    [self UploadAVAudioComplete:^(NSString *ImgName) {
        
        ImgName = [ImgName stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
        ImgName = [ImgName stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        
        // 新建按钮的
        UIButton *Button = [self CreatImgBtn:[UIImage imageNamed:@"btn_mp3"]];
        if (self.type == HNAssignmentTypeModifying) {
            Button.tag = 1002;
        }
        // 加入数组
        [self.ImgArr addObject:@{ImgName:Button}];
    }];
}

// 上传音频
- (void)UploadAVAudioComplete:(void(^)(NSString *ImgName))Complete
{
    [[UIApplication sharedApplication].keyWindow addSubview:[CourseEvaluateAudioView ConsumeSureWithClickCommit:^(BOOL IsSelect) {
        
        // 录音切换
        IsSelect ? [self MgrBeginAudio]:[self MgrCloseAudioComplete:Complete];
    }]];
}

/**
 开始录音
 */
- (void)MgrBeginAudio
{
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"download/aaa"];
    
    [[EMCDDeviceManager sharedInstance] asyncStartRecordingWithFileName:path completion:^(NSError *error)
     {
     }];
    
}

/**
 停止录间并上传
 */
- (void)MgrCloseAudioComplete:(void(^)(NSString *ImgName))Complete
{
    [[EMCDDeviceManager sharedInstance] asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
        
        if (recordPath.length != 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [MBProgressHUD showHUD];
                [NetManager UpdataAudioWithURL:LLBaseURLTeacher(@"upload.do") FilePath:recordPath parameter:@{@"action":@"uploadimage"} success:^(id obj) {
                    
                    NSString *Str = [[NSString alloc] initWithData:obj encoding:NSUTF8StringEncoding];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        // 上传成功，设置图片
                        Complete (Str);
                    });
                    
                } fail:^(NSError *error) {
                    [MBProgressHUD showError:@"音频上传失败"];
                }];
            });
        }
        
        // 主线程更新图片
    }];
}

#pragma mark - 点击了视频上传
- (void)ClickVideo:(UIButton *)Button {
    
    
    [self AlertControllerOfTitle:@"请选择视频选择方式" StringArr:@[@"拍摄", @"从相册中选择"] CallBack:^(NSInteger Index, NSString *Str) {
        if (Index == 0) {
            
            [self Action_GoCamera:Button];
        }
        
        if (Index == 1) {
            
            [self Action_Select:Button];
        }
    }];
}

/** 进入拍摄 */
- (void)Action_GoCamera:(UIButton *)Button{
    if (![self isSimulator]) {
        MBSmartVideoView *smart = [[MBSmartVideoView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        [self.navigationController.view addSubview:smart];
        __weak __typeof(&*self)weakSelf = self;
        [smart setFinishedRecordBlock:^(NSDictionary *info) {
            
            MyHappyTimeVC *vc = [MyHappyTimeVC new];
            
            vc.urlBlock = ^(NSString *urlStr, NSString *urlImg) {
                
                [weakSelf VideoUploadSuccessUrlStr:urlStr urlImg:urlImg ImgPath:[[info objectForKey:@"videoURL"] description]];
                
            };
            
            self.SaveVideo = YES;
            vc.VideoPath = [[info objectForKey:@"videoURL"] description];
            [self.navigationController pushViewController:vc animated:YES];
            
        }];
    } else {
        NSLog(@"模拟器不支持小视频录制");
    }
}

// 按钮改变
- (void)VideoUploadSuccessUrlStr:(NSString *)urlStr urlImg:(NSString *)urlImg ImgPath:(NSString *)ImgPath {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        UIButton *Button = [self CreatImgBtn:[self GetVideoPreViewImage:ImgPath]];
        // 视频的存储，@[@{Button.tag:@{@"url":url,@"img":img}}]
        [self.VideoDict addObject:@{@(Button.tag):@{@"url":urlStr,@"img":urlImg}}];
        self.SaveVideo = YES;
    });
    
}

/** 从相册中选择 */
- (void)Action_Select:(UIButton *)Button {
    
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
    pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    pickerImage.delegate = self;
    // 设定显示数据的类型，全部为视频
    pickerImage.mediaTypes = @[(NSString*)kUTTypeMovie,(NSString*)kUTTypeVideo,(NSString*)kUTTypeAudiovisualContent,(NSString*)kUTTypeAudio,(NSString*)kUTTypeQuickTimeMovie,(NSString*)kUTTypeMPEG,(NSString*)kUTTypeMPEG2Video,(NSString*)kUTTypeMPEG2TransportStream,(NSString*)kUTTypeMPEG4,(NSString*)kUTTypeMPEG4Audio,(NSString*)kUTTypeAppleProtectedMPEG4Audio,(NSString*)kUTTypeAppleProtectedMPEG4Video,(NSString*)kUTTypeAVIMovie,(NSString*)kUTTypeAudioInterchangeFileFormat,(NSString*)kUTTypeWaveformAudio,(NSString*)kUTTypeMIDIAudio];
    
    
    [pickerImage.navigationBar setBarTintColor:ColorRGB(58, 203, 140)];
    [pickerImage.navigationBar setTranslucent:NO];
    [pickerImage.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    [self presentViewController:pickerImage animated:YES completion:nil];
}

/** 获取视频的第一帧的图片 */
- (UIImage*)GetVideoPreViewImage:(NSString *)Str
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:Str] options:nil];
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *img = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return img;
}


#pragma mark - 相册代理
//适用获取所有媒体资源，只需判断资源类型
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    //如果是视频资源
    NSURL *sourceURL = info[UIImagePickerControllerMediaURL];
    
    if (sourceURL != nil) {
        [picker dismissViewControllerAnimated:YES completion:^{
            
            NSString *Str = [sourceURL absoluteString];
            Str = [Str substringFromIndex:8];
            NSInteger   fileSize = [[NSFileManager defaultManager] attributesOfItemAtPath:Str error:nil].fileSize / 1024 / 1024;
            if (fileSize <= 0)
            {
                MyHappyTimeVC *VC = [[MyHappyTimeVC alloc] init];
                VC.urlBlock = ^(NSString *urlStr, NSString *urlImg) {
                    
                    [self VideoUploadSuccessUrlStr:urlStr urlImg:urlImg ImgPath:Str];
                };
                
                VC.VideoPath = Str;
                [self.navigationController pushViewController:VC animated:YES];
            }
            else
            {
                NSString *Message = [NSString stringWithFormat:@"您选择的视频文件大小为%ld(兆)，上传需要花费较长时间，是否继续上传？",fileSize];
                // 跳转至视频上传
                UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:Message preferredStyle:(UIAlertControllerStyleAlert)];
                [Alert addAction:[UIAlertAction actionWithTitle:@"继续" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
                    MyHappyTimeVC *VC = [[MyHappyTimeVC alloc] init];
                    
                    VC.urlBlock = ^(NSString *urlStr, NSString *urlImg) {
                        
                        [self VideoUploadSuccessUrlStr:urlStr urlImg:urlImg ImgPath:Str];
                    };
                    
                    
                    VC.VideoPath = Str;
                    [self.navigationController pushViewController:VC animated:YES];
                }]];
                [Alert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
                [self presentViewController:Alert animated:YES completion:nil];
            }
        }];
    } else {
        
        // 图片
        [picker dismissViewControllerAnimated:YES completion:^{
            // 如果是图片
            UIImage *Img = info[UIImagePickerControllerOriginalImage];
            [self UploadImg:Img Complete:^(NSString *ImgName) {
                // 新建按钮的
                UIButton *Button = [self CreatImgBtn:Img];
                
                if (self.type == HNAssignmentTypeModifying) {
                    Button.tag = 1001;
                }
                // 加入数组
                [self.ImgArr addObject:@{ImgName:Button}];
                
            }];
            
        }];
    }
}

#pragma mark - 播放音视频方法
- (void)play:(UIButton *)sender {
    switch (sender.tag) {
        case 0:
            [self.webView loadRequest:[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:self.model.video]]];
            self.webView.hidden =NO;
            break;
        case 1001:
            [ImgZoom MgrButtonImgView:sender];
            break;
        case 1002:
            [self PlayerWithUrlStr:self.mp3URL];
            break;
        default:
            break;
    }
}

#pragma mark - 删除资源
- (void)deleteButton:(UIButton *)Button {
    [self AlertControllerOfTitle:@"是否删除该文件?" StringArr:@[@"确定"] CallBack:^(NSInteger Index, NSString *Str) {
        
        // 临时保存地
        __block NSDictionary *TempDict = nil;
        // 在字典里看下有没有
        [self.ImgArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            // 提出字典里面的value
            NSArray *ValueArr = [(NSDictionary *)obj allValues];
            // value肯定是button
            UIButton *objButton = (UIButton *)[ValueArr firstObject];
            // 判断一下,如果存放就保存这个字典
            if (Button == objButton)
            {
                // 保存下来
                TempDict = (NSDictionary *)obj;
            }
        }];
        // 如果按钮是视频的话
        [self.VideoDict enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSInteger Index = [[[obj allKeys] firstObject] integerValue];
            if (Button.tag == Index) {
                
                [self.VideoDict removeObject:obj];
                self.SaveVideo = NO;
                *stop = YES;
            }
        }];
        // 检查这个TempDict，有值说明这个button已经有数据了,清除掉
        TempDict ? [self.ImgArr removeObject:TempDict] : nil;
        
        [self MoveUploadFileBtnLeftOfAdd:NO Button:Button];
        
    }];
}



- (void)PlayerWithUrlStr:(NSString *)UrlStr
{
    if ([EMCDDeviceManager sharedInstance].isPlaying) {
        [[EMCDDeviceManager sharedInstance] stopPlaying];
    } else {
        [self RefreshDataForAmr:UrlStr Complete:^(NSString *FullPath) {
            
            FullPath = [FullPath substringFromIndex:7];
            [[EMCDDeviceManager sharedInstance] asyncPlayingWithPath:FullPath completion:^(NSError *error) {
                NSLog(@"播放完成");
            }];
        }];
    }
}

- (void)RefreshDataForAmr:(NSString *)UrlStr Complete:(void(^)(NSString *FullPath))Complete
{
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"AMR"];
    [NetManager DownLoadFileWithUrlStr:UrlStr FileName:[UrlStr lastPathComponent] Path:path Progress:^(CGFloat Index) {
        
    } Complete:^(NSString *FullPath, NSError *Err) {
        [MBProgressHUD hideHUD];
        if (Err)
        {
            [MBProgressHUD showError:@"音频文件播放失败"];
        }
        else
        {
            Complete (FullPath);
        }
    }];
    
}

#pragma mark UIWebDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    self.webView =nil;
}



- (UIWebView *)webView{
    if (_webView == nil) {
        self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(1, 1, 1, 1)];
        self.webView.delegate =self;
        [self.view addSubview:self.webView];
    }
    return _webView;
}


- (BOOL)isSimulator {
#if TARGET_OS_SIMULATOR
    return YES;
#else
    return NO;
#endif
}

- (UIImagePickerController *)ImagePicker
{
    if (!_ImagePicker)
    {
        _ImagePicker = [[UIImagePickerController alloc] init];
        _ImagePicker.delegate = self;
        _ImagePicker.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        _ImagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        _ImagePicker.navigationBar.tintColor = [UIColor whiteColor];
        _ImagePicker.navigationBar.barTintColor = [UIColor colorWithRed:20.f/255.0 green:24.0/255.0 blue:38.0/255.0 alpha:1];
    }
    return _ImagePicker;
}

- (NSMutableArray<UIButton *> *)ImgBtns {
    
    if (!_ImgBtns) {
        
        _ImgBtns = [NSMutableArray array];
    }
    return _ImgBtns;
}

- (NSMutableArray *)ImgArr
{
    if (!_ImgArr)
    {
        _ImgArr = [NSMutableArray array];
    }
    return _ImgArr;
}

- (NSMutableArray *)VideoDict {
    
    if (!_VideoDict) {
        
        _VideoDict = [NSMutableArray array];
    }
    return _VideoDict;
}

@end

